package com.dirox.plugins.jira.servlet;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.atlassian.jira.bc.issue.search.SearchService;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.search.SearchException;
import com.atlassian.jira.jql.builder.JqlClauseBuilder;
import com.atlassian.jira.jql.builder.JqlQueryBuilder;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.project.ProjectManager;
import com.atlassian.jira.security.JiraAuthenticationContext;
import com.atlassian.jira.user.util.UserManager;
import com.atlassian.jira.web.bean.PagerFilter;
import com.dirox.plugins.ao.Note;
import com.dirox.plugins.ao.NoteService;

//import com.atlassian.sal.api.user.UserManager;

public class ProcessServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private final JiraAuthenticationContext context;
	private NoteService noteService;
	private UserManager userManager;
	private SearchService searchService;
	private ProjectManager projectManager;

	// private com.atlassian.jira.user.util.UserManager userManager1;

	public List<Issue> getIssues(String projectName) {
		final com.atlassian.crowd.embedded.api.User currentUser = context
				.getLoggedInUser();
		JqlClauseBuilder jqlClauseBuilder = JqlQueryBuilder.newClauseBuilder();
		com.atlassian.query.Query query = jqlClauseBuilder.project(projectName)
				.buildQuery();
		PagerFilter pagerFilter = PagerFilter.getUnlimitedFilter();
		com.atlassian.jira.issue.search.SearchResults searchResults = null;
		try {
			searchResults = searchService.search(currentUser, query,
					pagerFilter);
		} catch (SearchException e) {
			e.printStackTrace();
		}
		return searchResults.getIssues();
	}

	public List<Issue> getIssues() {
		List<Issue> issues = new ArrayList<Issue>();
		List<Project> projects = projectManager.getProjectObjects();
		for (Project p : projects) {
			issues.addAll(getIssues(p.getName()));
		}
		return issues;
	}

	public Issue getIssue(String key) {
		for (Issue i : getIssues()) {
			if (i.getKey().equals(key)) {
				return i;
			}
		}
		return null;
	}

	public ProcessServlet(JiraAuthenticationContext context,
			NoteService noteService, UserManager userManager,
			SearchService searchService, ProjectManager projectManager) {
		this.context = context;
		this.noteService = checkNotNull(noteService);
		this.userManager = checkNotNull(userManager);
		this.searchService = checkNotNull(searchService);
		this.projectManager = checkNotNull(projectManager);
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		enforceLoggedIn(request, response);
		response.setContentType("text/html;charset=UTF-8");

		HttpSession session = request.getSession();
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		if (request.getParameter("action") != null) {
			String action = request.getParameter("action");
			com.atlassian.crowd.embedded.api.User currentUser = context
					.getLoggedInUser();

			if (action.equals("Create")) {
				if (request.getParameter("content") != null
						&& request.getParameter("content").equals("") == false) {
					String content = request.getParameter("content");
					String priority = request.getParameter("priority");
					Note note = noteService.add(content,
							Integer.parseInt(priority));
					if (request.getParameter("noteid") == null
							|| request.getParameter("noteid").length() == 0) {
						if (request.getParameter("user") != null
								&& request.getParameter("user").equals("-1") == false) {
							String userName = request.getParameter("user");
							com.atlassian.crowd.embedded.api.User user = userManager
									.getUser(userName);
							noteService.tagNoteToUser(note, user);
						}
					} else {
						int noteid = Integer.parseInt(request
								.getParameter("noteid"));
						String userName = context.getLoggedInUser().getName();
						noteService.untagNoteToUser(noteid, userName);
					}

					if (request.getParameter("issue") != null
							&& request.getParameter("issue").equals("-1") != true) {
						String issueKey = request.getParameter("issue");
						Issue issue = getIssue(issueKey);
						noteService.tagNoteToIssue(note, issue);
					}
					response.sendRedirect(request.getContextPath()
							+ "/secure/ViewProfile.jspa");
				}
			} else if (action.equals("Delete")) {
				int id = Integer.parseInt(request.getParameter("id"));
				noteService.delete(id);
				response.sendRedirect(request.getContextPath()
						+ "/secure/ViewProfile.jspa");
			} else if (action.equals("Update")) {
				if (request.getParameter("id") != null) {
					int id = Integer.parseInt(request.getParameter("id"));
					if (request.getParameter("content") != null) {
						String content = request.getParameter("content");
						int priority = -1;
						if (request.getParameter("priority") != null) {
							priority = Integer.parseInt(request
									.getParameter("priority"));
						}
						Note note = noteService.update(id, content, priority);

//						if (request.getParameter("user") != null
//								&& request.getParameter("user").equals("-1") != true) {
//							String userName = request.getParameter("user");
//							com.atlassian.crowd.embedded.api.User user = userManager
//									.getUser(userName);
//							noteService.tagNoteToUser(note, user);
//						}
//
//						if (request.getParameter("issue") != null
//								&& request.getParameter("issue").equals("-1") != true) {
//							String issueKey = request.getParameter("issue");
//							Issue issue = getIssue(issueKey);
//							noteService.tagNoteToIssue(note, issue);
//						}

						response.sendRedirect(request.getContextPath()
								+ "/secure/ViewProfile.jspa");
					} else {
						Note note = noteService.getNote(id);
						out.println("<body id='main_body' > ");
						out.println(" <div id='form_container'>");

						out.println("<form id='formUpdate' action='processservlet' method='get'>");
						out.println("  <div align='center' class='field-group'>");
						out.println("  <h1><a>Update Note</a></h1>");
						out.println("   <table>");
						out.println("    <tr>");
						out.println("     <td>Priority<br />");

						if (note.getPriority() == 1) {
							out.println("     <input id='idMust' type='radio' name='priority' value='1' checked='yes' />Must<br />");
							out.println("     <input id='idCould' type='radio' name='priority' value='2' />Could<br /></td>");
						} else {
							out.println("     <input id='idMust' type='radio' name='priority' value='1' />Must<br />");
							out.println("     <input id='idCould' type='radio' name='priority' value='2'  checked='yes'/>Could<br /></td>");
						}

						out.println("     <td rowspan='3'`><textarea id='idContent' class='element textarea' name='content' rows='10' cols='50'>"
								+ note.getContent() + "</textarea></td>");
						out.println("    </tr>");
						out.println("    <tr>");
						if (note.getUsers().length == 0) {
							out.println("     <td>Users Tagged<br /> <select name='user'>");
							out.println("       <option value='-1'>none</option>");

							List<com.atlassian.crowd.embedded.api.User> users = new ArrayList<com.atlassian.crowd.embedded.api.User>();
							users.addAll(userManager.getAllUsers());
							users.remove(currentUser);
							for (com.atlassian.crowd.embedded.api.User u : users) {
								out.println("       <option value='"
										+ u.getName() + "'>" + u.getName()
										+ "</option>");
							}
							out.println("     </select></td>");
						}
						out.println("    </tr>");
						out.println("    <tr>");

						if (note.getIssues().length == 0) {
							out.println("     <td>Issues Tagged<br />");
							out.println("     <select name='issue'>");
							out.println("       <option value='-1'>none</option>");
							for (Issue issue : getIssues()) {
								out.println("       <option value='"
										+ issue.getKey() + "'>"
										+ issue.getKey() + "</option>");
							}
							out.println("     </select></td>");
						}
						out.println("    </tr>");
						out.println("   </table>");
						out.println("   <input class='text' type='submit' name='update' value='Update' />");
						out.println("   <a href='/jira/plugins/servlet/processservlet?action=Delete&id="
								+ id + "'>Delete</a>    ");
						out.println("   <input class='text' type='hidden' name='action' value='Update' />");
						out.println("   <input class='text' type='hidden' name='id' value='"
								+ id + "' />");
						out.println("  </div>");
						out.println(" </form>");
						out.println(" </div>");
						out.println("</body>");
					}
				}
			}
		}
	}

	private void enforceLoggedIn(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		// if (userManager.getRemoteUsername() == null) {
		// res.sendRedirect(req.getContextPath() + "/plugins/servlet/login");
		// }
	}
}
